﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Volo.Abp.BlobStoring;

namespace Jy.Abp.BlobStoring;

public static class IBlobContainerExtensions
{
    private static IDictionary<Type, Lazy<BlobContainerCacheItem>> _nameDic
        = new Dictionary<Type, Lazy<BlobContainerCacheItem>>();

    public static BlobContainerCacheItem GetCacheItem(this IBlobContainer container)
    {
        var containnerType = container.GetType();
        return _nameDic.GetOrAdd(containnerType, type =>
        {
            return new Lazy<BlobContainerCacheItem>(() =>
            {
                var obj = container;
                var objType = type;
                if (type.IsGenericType)
                {
                    obj = containnerType
                        .GetField("Container", BindingFlags.NonPublic | BindingFlags.Instance)
                        .GetValue(container) as IBlobContainer;
                    objType = obj.GetType();
                }
                var name = objType
                    .GetProperty("ContainerName", BindingFlags.NonPublic | BindingFlags.Instance)
                    .GetValue(obj)?
                    .ToString();
                var config = objType
                    .GetProperty("Configuration", BindingFlags.NonPublic | BindingFlags.Instance)
                    .GetValue(obj) as BlobContainerConfiguration;
                return new BlobContainerCacheItem(name, config);
            });
        }).Value;
    }

    public static string GetName(this IBlobContainer container)
    {
        return container.GetCacheItem().Name;
    }

    public static BlobContainerConfiguration GetConfiguration(this IBlobContainer container)
    {
        return container.GetCacheItem().Configuration;
    }
}
